//xuejianxin@20180101
(function (){
//App全局上下文,以_开头的变量约定不要直接访问,比如_user,应该调用getUser方法
var AppContext={
		rootPath :"/" //应用的全局根目录 /bwieApp/
	    //rootPath :"bwieApp" //应用的全局根目录 
		,_user    :null//用户缓存	 
		,_codeUrl :"demo/loadCode"  //代码请求url,根据需要修改	 
		,codeMap  :{//全局代码缓存
			 truefalse:{'1':'是','0':'否'}//是否
            ,sex      :{'1':'男','0':'女'}//性别
		}
        ,toJson         :function (obj) {return JSON.stringify(obj);}/*js对象转化为json字符串*/
        ,parseJson      :function (json){return JSON.parse(json);}/*json字符串转化为js对象*/
        ,setUser        :function (user){delete user.password;this._user=user;this.setLocalItem("user",this.toJson(user));}/*设置用户*/
        ,getUser        :function ()    {if(this._user){return this._user; } else{ return this.parseJson(this.getLocalItem("user"));}}/*获取当前用户信息*/
        ,logout         :function ()    {this.removeLocalItem("user");window.location.href=this.rootPath;}/*登出*/
        ,setItem        :function (k,v) {sessionStorage.setItem(k, v);}/*设置 sessionStorage 变量*/
        ,removeItem     :function (k)   {sessionStorage.removeItem(k);}/*移除sessionStorage 变量*/
        ,getItem        :function (k)   {return sessionStorage.getItem(k);}/*获取 sessionStorage 变量*/
        ,setLocalItem   :function (k,v) {localStorage.setItem(k, v);}/*设置 localStorage 变量*/
        ,removeLocalItem:function (k)   {localStorage.removeItem(k);}/*移除localStorage 变量*/
        ,getLocalItem   :function (k)   {return localStorage.getItem(k);}/*获取 localStorage 变量*/
        ,loadCode       :function (codeArray /*codeArray是一个数组*/){/*缓存代码*/
        	var codes=[];
        	//先检查缓存如果缓存中存在就不重复请求
        	for(i in codeArray){
        		var code=codeArray[i];
        		if(!this.codeMap[code]){
        			codes.push(code);
        			//设置空对象标识已经开始加载数据
        			this.codeMap[code]={};
        		}
        	}
        	if(codes.length>0){
        	  Vue.http.post(this._codeUrl,codes).then(successCallback,Vue.http.error);
        	}
        	function successCallback(response){
        		var result=response.data;
        		for(i in codes){
        			var code=codes[i];
        			AppContext.codeMap[code]=result[code];
        		}
        	}
        },
        getParameters:function () {  
      	  var qs = location.search.substr(1), // 获取url中"?"符后的字串  
      	    args = {}, // 保存参数数据的对象
      	    items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
      	    item = null,
      	    len = items.length;
      	 
      	  for(var i = 0; i < len; i++) {
      	    item = items[i].split("=");
      	    var name = decodeURIComponent(item[0]),
      	      value = decodeURIComponent(item[1]);
      	    if(name) {
      	      args[name] = value;
      	    }
      	  }
      	  return args;
      }
        
};//AppContext

//导出为全局变量
function _export(k,v){window[k]=v;}
_export('AppContext',AppContext);

Vue.http.options.root = AppContext.rootPath;//vue ajax请求的根路径	
Vue.http.interceptors.push(function (request, next) {
	  //调用等待框，此处的 this 为发起请求的 component
	  loading.show();
	  next(function (response) {
	  	loading.hide();
	    // 消掉等待框，此处的 this 为发起请求的 component
	  	return response;
	  })
});
//ajax 全局错误处理
Vue.http.error=function(response) {
	if( '401'==response.status){
  		AppContext.logout();
  		return ;
  	} else if( '403'==response.status){
  		dialog.alert('您没有权限!');
  		return ;
  	}else{
	    dialog.alert({'title':'系统错误','message':'系统请求错误 !状态码:'+response.status});
  	}
};
//vue 全局错误处理
/*
Vue.config.errorHandler = function (err, vm, info) {
	console.log(err);
	console.log(vm);
	console.log(info);
	//由于前台错误在微信端,线上环境很难捕获错误,发送到后台处理
	var errorMessage={
		  "vmErr" :err
		 ,"vmUrl" :vm.$el.baseURI //请求路径
		 ,"vmInfo":info
		 ,"userId":AppContext.__user.username
	};
	//console.log(errorMessage);
	Vue.http.post("error",errorMessage);
	
}*/
var comps=[];

var my_toolbar={
		  tagName :'my_toolbar'
		, desc    :'工具栏'
		, options :{
		  data:function (){ return {  rootPath:AppContext.rootPath}}
		, props: {
		   showmenu     :{type: Boolean ,'default':false}
		}
		,mounted: function() {
			if(!this.showmenu){
				return ;
			}
			var n =false;
		    $("#sidebar-collapse").on("click", function() {
		    	$(".sidebar-collapse").toggleClass("active");
		    	$("#sidebar").toggleClass("hide");
		    });
		    $(".sidebar-menu").on("click", function(t) {
		        var i = $(t.target).closest("a"), u, r, f;
		        if (i && i.length != 0) {
		            if (!i.hasClass("menu-dropdown"))
		                return n && i.get(0).parentNode.parentNode == this && (u = i.find(".menu-text").get(0),
		                t.target != u && !$.contains(u, t.target)) ? !1 : void 0;
		            if (r = i.next().get(0),
		            !$(r).is(":visible")) {
		                if (f = $(r.parentNode).closest("ul"),
		                n && f.hasClass("sidebar-menu"))
		                    return;
		                f.find("> .open > .submenu").each(function() {
		                    this == r || $(this.parentNode).hasClass("active") || $(this).slideUp(200).parent().removeClass("open")
		                })
		            }
		            return n && $(r.parentNode.parentNode).hasClass("sidebar-menu") ? !1 : ($(r).slideToggle(200).parent().toggleClass("open"),
		            !1)
		        }
		    })
		}
		,methods:{}
		,template:
		'<div class="my-toolbar">\
			  <i class="toolbar-item fa fa-bars" id="sidebar-collapse" v-if="showmenu" ></i>\
			  <slot></slot>\
		 </div>'
		}};
var my_menu={
		  tagName :'my_menu'
		, desc    :'菜单栏组件'
		, options :{
		 data:function (){ 
			 return { rootPath:AppContext.rootPath 
				    ,memus:[]
			 }
		}
		,mounted: function() {
			this.reloadMenus();
		}
		,methods:{
			reloadMenus:function (){
				var parameters={};
				this.$http.post("/reloadMenus",parameters, {headers: {}})
		   	    .then(function(response) {//正确响应
		   	    	var data=response.data;
		   	    	if(data){
		   	    		this.memus=data.list;
		   	    	}
		   	    }
		   	    ,function(response) {//处理错误
		   	    	this.$http.error(response);
		   	    });
			} 
		}
		,template:
		'<div class="page-sidebar" id="sidebar" style="z-index: 12;left:0px" ><ul class="nav sidebar-menu " >\
			<li v-for="m in memus">\
			  <a :href="m.link" v-bind:class="{ \'menu-dropdown\': m.hasChildren }">\
                <i :class="m.icon"></i>\
                <span class="menu-text">{{m.name}}</span>\
			    <i class="menu-expand" v-if="m.hasChildren"></i>\
              </a>\
			  <ul class="submenu" v-if="m.hasChildren">\
			     <li v-for="sm in m.submenu" >\
					<a :href="sm.link"><span class="menu-text">{{sm.name}}</span></a>\
			     </li>\
			  </ul>\
	        </li>\
			<li><a href="#" onclick="AppContext.logout()"><i class="menu-icon fa  fa-user"></i><span class="menu-text">退出系统</span></a></li>\
	     </ul></div>'
		}};
var my_page={
		tagName :'my_page'
	  , desc    :'分页组件'
	  , options :{
 props: ['currentPage','pageCount','pageSize','count']
,computed: {//计算属性
	isFirstPage:function (){//是否第一页
	   return  1==this.currentPage?"disabled":"";
	}
    ,isLastPage:function(){//是否最后一页
  	   return  this.pageCount==this.currentPage?"disabled":""
    }
}
,methods:{
	previousPage: function (){//前一页
   	 if(this.currentPage>1 ){
   		this.$emit('page_change' ,{count:-1});//发送事件给父组件
   	 }
    }
    ,nextPage :function (){//后一页
   	 if(this.currentPage<this.pageCount ){
   		 this.$emit('page_change',{count:1});//发送事件给父组件
   	 }
    }
}
,template:
'<ul class="pager draggable" >\
	<li style="display: block;" v-bind:class="isFirstPage" @click="previousPage" @touchstart="previousPage"><a style="border: none; display: block;border-radius:10px;padding: 5px 0px;margin-bottom: 2px" href="javascript:void(\'0\');"  class="glyphicon glyphicon-chevron-left"></a></li>\
	<li style="display: block;"><a style="border: none;display: block;border-radius:10px;padding: 5px 0px" href="javascript:void(\'0\');">{{currentPage}}/{{pageCount}}</a></li>\
	<li style="display: block;" v-bind:class="isLastPage" @click="nextPage" @touchstart="nextPage"><a style="border: none;display: block;border-radius:10px;padding: 5px 0px" href="javascript:void(\'0\');" class="glyphicon glyphicon-chevron-right"></a></li>\
</ul>'
}//options
};//my_pager
//样例:<my_code_select code_type='qjlx'  name="qjlx" class="form-control" v-model="vo.qjlx">请选择请假类型</my_code_select>
var my_code_select={
		tagName :'my_code_select'
	  , desc    :'代码下拉框[code_type:代码类型,必填;value:默认选中代码值,非必填]'
	  , options :{ props: {
		                   code_type:{type: String,required: true}
                          ,value    :{required: false}//默认选中的值
		          }
                  ,model: {prop: 'value',event: 'change'}
                  ,data:function (){return {codeMap:AppContext.codeMap}}
                  ,template:'<select v-on:change="updateValue($event.target.value)"><option value ="">请选择</option><option v-for="(val, key) in codeMap[code_type]" :selected="key==value" :value="key">{{val}}</option></select>'
                  ,methods: {
                	   updateValue: function (value) {
                		  this.$emit('change', value);
                	   }
                  }
	  }//options
};//my_code_select

var my_code_checkbox={
		tagName :'my_code_checkbox'
	  , desc    :'代码checkbox或radio[code_type:代码类型,必填;checked:默认选中代码值,非必填;type:是checkbox还是radio ]'
	  , options :{ props: {
		                    code_type:{type: String,required: true}
                           ,checked  :{required: false}
                           ,type     :{type: String,'default': 'checkbox'}
                           ,name     :{type: String,required: true}
                  }
                  ,data:function (){return {codeMap:AppContext.codeMap}}
                  ,model: {prop: 'checked',event: 'change'}
                  ,methods: {
          		      updateValue: function (who) {
          		    	var isChecked=who.checked;
          		    	if(this.type=='checkbox'){
	          		    	var has=false;
	          		    	var newChecked=[];
	          		    	if(this.checked){
	          		    		//先拷贝 除 who.value 之外的其他值
	          		    		for(i in this.checked){
	          		    			if( this.checked[i]!=who.value){
	                  					newChecked.push(this.checked[i]);
	                  				}
	          		    		}
	          		    	}
	          		    	if(isChecked){
	          		    		//如果被选中 加到集合中
	          		    		newChecked.push(who.value);
	          		    	}
	          		    	this.$emit('change', newChecked);
          		    	}else{//radio
          		    		if(isChecked){
          		    		  this.$emit('change', who.value);
          		    		}
          		    	}
          		      }//updateValue
                	  ,setChecked:function(key){
                		  //计算属性不能传值，只能利用已有参数做出相应的某种变化,想使用灵活需要内部依赖的参数变化来调整,使用methods来做，根据传参返回不同的值
                		  if(this.checked){
                			  for(i in this.checked){
                				  if(this.checked[i]==key){ return true;}
                			  }
                		  }
                		  return false;
                	  }  
                  }
                  ,template:'<span><label v-for="(val, key) in codeMap[code_type]"><input ref="myCheck" :name="name" :type="type" :value="key" :checked="setChecked(key)" v-on:change="updateValue($event.target)" >{{val}}<slot name="space">&nbsp;</slot></label></span>'
        }//options
};//my_code_checkbox
//样例:<my_input_date  class="form-control" id="beginDate" placeholder="请假开始时间" v-model="vo.beginDate"></my_input_date>
var my_input_date={
		tagName :'my_input_date'
	  , desc    :'日期组件[]'
	  , options :{ props: {
                           value  :{required: true}//默认选中的值
                          ,time   :{required: false,'default':true}//是否包含时间
		          }
                  ,template:'<input type="date" v-bind:value="value|my_fn_split" v-on:input="updateValue($event.target.value)" >'
                  ,methods: {
                	   updateValue: function (newValue) {
                		  newValue= newValue+ (time?' 00:00:00':'');
                		  this.$emit('input', newValue);
                	   }
                  }
	  }//options
};//my_input_date

comps.push(my_toolbar);
comps.push(my_menu);
comps.push(my_page);
comps.push(my_code_select);
comps.push(my_code_checkbox);
comps.push(my_input_date);
for(i in comps){
   Vue.component(comps[i].tagName,comps[i].options);//注册全局组件	
}
/*代码翻译过滤器
 *用法: {{'1'|my_code_name('truefalse')}} 
 *从 truefalse 代码组中翻译 1 的名称,结果:男
 */
Vue.filter('my_code_name', function (code_key,code_type) {
	  var result='';
	  var codes=AppContext.codeMap[code_type];
	  if(codes){
		  result= codes[code_key];
	  }
	  return result;
});
/*分割字符串 
 * 用法 
 * {{'aa bb cc'|my_fn_split}} 结果: aa
 * {{'aa,bb,cc'|my_fn_split(',','2')}} 结果: cc
*/
Vue.filter('my_fn_split', function (str/*值*/,separator/*分隔符默认为空格*/,index/*返回哪一部分*/) {
	var result='';
	if(str){
		separator=separator?separator:' ';
		index=index?index:0;
		var vs= str.split(separator);
		if(vs.length>index){
			result= vs[index];
		}
	}
	return result;
});
/*截取字符串
 * 用法:
 * {{'0123456789ABC'|my_fn_substring}} 结果: 0123456789...
 * {{'0123456789ABC'|my_fn_substring(5,'更多...')}} 结果: 01234更多...
 */ 
Vue.filter('my_fn_substring', function (str/*值*/,len/*截取长度*/,suffix/*后缀*/) {
	var result='';
	if(str){
		len=len?len:10;
		suffix=suffix?suffix:'...';
		result=str.substring(0,Math.min(str.length,len));
	}
	return result;
});


//js 组件
var loading={
		_id:'#_loading_div'
		,show: function (){
			var obj=$(this._id); 
			if(obj.length <= 0){$(document.body).append(this._html);obj=$(this._id);} 
			obj.css({display:'block'});
		},
		hide:function(){$(this._id).css({display:'none'});}
		,_html:'<div id="_loading_div" style="display:none;position:fixed;top:40%;left:45%"><img alt="加载中..." src="'+AppContext.rootPath+'resources/app/img/loader.gif"><div>'
}

var dialog={
		 alert:function (options){
			 //backdrop可选值:true,false 'static',static必须强制手动关闭
			 var defautOptions={backdrop: true};
			 if(typeof options ==='string'){//兼容直接传入字符串
		    		options={"message":options};
		     }
		     var options= jQuery.extend(true,defautOptions, options);
			 bootbox.alert(options);
		 }
		,confirm:bootbox.confirm
		,prompt :bootbox.prompt
		,dialog :bootbox.dialog
}
_export('dialog',dialog);
})();
